/*
� 最佳准确率窗口:
{
  windowSize: 21,
  total: 1244,
  correct: 852,
  accuracy: 68.49,
  maxWrongStreak: 7
}

� 最小连续错误窗口:
{
  windowSize: 3,
  total: 1244,
  correct: 815,
  accuracy: 65.51,
  maxWrongStreak: 5
}

*/
// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

/**
 * 获取斐波那契序列中不超过 max 的数字集合
 */
function getFibonacciPositions(max) {
  const fib = [1, 2];
  while (true) {
    const next = fib[fib.length - 1] + fib[fib.length - 2];
    if (next > max) break;
    fib.push(next);
  }
  return fib;
}

/**
 * 斐波那契分布策略
 * - 统计窗口内号码频率，按频率排序后取斐波那契下标号码
 */
function select32ByFibonacci(temp) {
  const freqMap = {};

  temp.forEach((item) => {
    const num = item.number;
    freqMap[num] = (freqMap[num] || 0) + 1;
  });

  const sorted = allNumbers
    .map((num) => ({
      number: num,
      count: freqMap[num] || 0,
    }))
    .sort((a, b) => b.count - a.count || a.number.localeCompare(b.number));

  const fibPositions = getFibonacciPositions(sorted.length);
  const selectedSet = new Set();

  fibPositions.forEach((pos) => {
    if (pos - 1 < sorted.length) {
      selectedSet.add(sorted[pos - 1].number);
    }
  });

  for (let i = 0; i < sorted.length && selectedSet.size < 32; i++) {
    selectedSet.add(sorted[i].number);
  }

  const selected = Array.from(selectedSet);
  if (selected.length !== 32) {
    throw new Error(`❗ 选出号码不足 32 个（实际 ${selected.length}）`);
  }

  return selected;
}

// ✅ 多窗口循环测试
const testResults = [];

for (let windowSize = 2; windowSize <= 200; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = allValues.slice(Math.max(0, index - windowSize), index);
    if (!temp.length) return;

    const selectedNumbers = select32ByFibonacci(temp);

    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }

    predictResults.push(selectedNumbers);
  });

  const total = predictResults.length;
  const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

  testResults.push({
    windowSize,
    total,
    correct,
    accuracy: Number(accuracy),
    maxWrongStreak,
  });
}

// ✅ 输出每个窗口的统计结果
// testResults.forEach((res) => {
//   console.log(
//     `windowSize = ${res.windowSize}, 准确率 = ${res.accuracy}%, 最大连续错误次数 = ${res.maxWrongStreak}`
//   );
// });

// ✅ 输出最佳准确率与最小连续错误结果
const bestAcc = _.maxBy(testResults, "accuracy");
const bestStable = _.minBy(testResults, "maxWrongStreak");

console.log("\n📊 最佳准确率窗口:");
console.log(bestAcc);

console.log("\n🧱 最小连续错误窗口:");
console.log(bestStable);
